package com.itheima.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.common.MessageConstant;
import com.itheima.common.exception.CheckItemException;
import com.itheima.pojo.*;
import com.itheima.service.AuthorityService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @version V1.0
 * @author: sujiahao
 * @date: 2020/2/12 11:10
 * @description:
 */
@RestController
@RequestMapping("/authority")
public class AuthorityController {

    @Reference
    private AuthorityService authorityService;

    /**
     * 根据条件进行查询
     *
     * @param queryPageBean
     * @return
     */
    @RequestMapping("/queryPage")
    public PageResult queryPage(@RequestBody QueryPageBean queryPageBean) {
        try {
            PageResult pageResult = authorityService.queryPage(queryPageBean);
            return new PageResult(pageResult.getTotal(), pageResult.getRows(), "查询权限成功", true);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult("查询权限失败", false);
        }
    }

    /**
     * 添加权限
     * @param permission
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Permission permission) {
        try {
            authorityService.add(permission);
            return new Result(true, "新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "新增失败");
        }
    }


    /**
     * 根据id查询数据，用于数据编辑时的数据回显
     *
     * @param id
     * @return
     */
    @RequestMapping("/queryById")
    public Result queryById(Integer id) {
        try {
            Permission permission = authorityService.queryById(id);
            return new Result(true, "成功", permission);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "失败");
        }
    }

    /**
     *
     *修改权限
     * @param permission
     * @return
     */
    @RequestMapping("/updataById")
    public Result updataById(@RequestBody Permission permission) {
        try {
            authorityService.updataById(permission);
            return new Result(true, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改失败");
        }
    }

    /**
     * 根据id进行数据的删除
     * @param id
     * @return
     */
    @RequestMapping("/deleteById")
    public Result deleteById(Integer id) {
        try {
            authorityService.deleteById(id);
            return new Result(true, "删除成功");
        } catch (CheckItemException e) {
            return new Result(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除失败");
        }
    }

}
